package test.serverframe.armc.server.manager.controller;

import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import test.serverframe.armc.server.manager.common.ResultDtoUtil;
import test.serverframe.armc.server.manager.common.exception.ExceptionHandle;
import test.serverframe.armc.server.manager.controller.params.IntegrationTestPageParams;
import test.serverframe.armc.server.manager.controller.params.IntegrationTestRecordPageParams;
import test.serverframe.armc.server.manager.controller.vo.*;
import test.serverframe.armc.server.manager.domain.ConfigManager;
import test.serverframe.armc.server.manager.domain.IntegrationTest;
import test.serverframe.armc.server.manager.domain.IntegrationTestInterfaceRecord;
import test.serverframe.armc.server.manager.domain.IntegrationTestInterfaceUseCaseRecordAsso;
import test.serverframe.armc.server.manager.domain.TestUseCaseRecord;
import test.serverframe.armc.server.manager.dto.ResultDto;
import test.serverframe.armc.server.manager.service.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * @author LeiZhenYang
 * @date 2018.11.29
 */
@RestController
@RequestMapping("integration/test")
@CrossOrigin(origins = "*")
@Api("集成测试")
public class IntegrationTestController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(IntegrationTestController.class);

    /**
     * 集成测试服务
     */
    @Autowired
    private IntegrationTestService service;

    /**
     * 集成测试接口记录服务
     */
    @Autowired
    private IntegrationTestInterfaceRecordService itirService;

    /**
     * 集成测试记录服务
     */
    @Autowired
    private IntegrationTestRecordService integrationTestRecordService;

    /**
     * 测试用例服务
     */
    @Autowired
    private TestUseCaseService testUseCaseService;

    /**
     * 测试用例记录服务
     */
    @Autowired
    private TestUseCaseRecordService testUseCaseRecordService;

    /**
     * 任务分页自定义异常
     */
    @Autowired
    private ExceptionHandle<PageInfo<IntegrationTestPage>> exceptionHandleIntegrationTestPage;

    /**
     * 任务分页自定义异常
     */
    @Autowired
    private ExceptionHandle<PageInfo<IntegrationTestRecordPage>> exceptionHandleIntegrationTestRecordPage;
    
    /**
     * 配置管理服务
     */
    @Autowired
    private ConfigManagerService configManagerService;


    /**
     * 集成测试分页
     *
     * @param params
     * @return
     */
    @GetMapping("/page")
    @ApiOperation(notes = "集成测试分页", value = "集成测试分页")
    public ResultDto<PageInfo<IntegrationTestPage>> page(@ModelAttribute @Valid IntegrationTestPageParams params) {
        ResultDto<PageInfo<IntegrationTestPage>> result;
        try {
            PageInfo<IntegrationTestPage> mbrValues = service.pageFind(params.getPageNum(), params.getPageSize(), params);
            for(IntegrationTestPage i : mbrValues.getList()){
                    List list=itirService.getRecordByItrId(i.getLastTestRecordId());
                    i.setTestUseCaseRecords(list);
            }
            result = ResultDtoUtil.success(mbrValues);


        } catch (Exception ex) {
            logger.error(ex.getMessage());
            result = exceptionHandleIntegrationTestPage.exceptionGet(ex);
        }
        return result;
    }

    /**
     * 批量删除集成测试
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    @ApiOperation(notes = "批量删除集成测试", value = "批量删除集成测试")
    public ResultDto<Boolean> delete(@ApiParam("集成测试ID集合") @RequestBody List<String> ids) {
        if (ids != null) {
            ids.forEach(id -> service.deleteIntegrationTest(id));
        }
        return ResultDtoUtil.success();
    }


    /**
     * 根据集成测试记录ID获取集成接口测试记录
     *
     * @param itrId
     * @return
     */
    @GetMapping("interfaces/{itrId}")
    @ApiOperation(notes = "根据集成测试记录ID获取集成接口测试记录", value = "根据集成测试记录ID获取集成接口测试记录")
    public ResultDto<List<IntegrationTestInterfaceRecord>> getInterfacesByItrId(@ApiParam("集成测试记录主键") @PathVariable String itrId) {
        return ResultDtoUtil.success(itirService.getRecordByItrId(itrId));
    }

    /**
     * 根据集成测试记录ID获取集成接口测试记录
     *
     * @param itirId
     * @return
     */
    @GetMapping("/interface/usecases/{itirId}")
    @ApiOperation(notes = "根据集成测试接口记录ID获取集成测试接口测试的用例测试记录", value = "根据集成测试接口记录ID获取集成测试接口测试的用例测试记录")
    public ResultDto<List<TestUseCaseRecord>> getUseCaseByItirId(@ApiParam("集成测试记录主键") @PathVariable String itirId) {
        return ResultDtoUtil.success(testUseCaseRecordService.getRecordByItirId(itirId));
    }

    /**
     * 新增集成测试
     *
     * @param record
     * @return
     */
    @PostMapping
    @ApiOperation(notes = "新增集成测试", value = "新增集成测试")
    public ResultDto<Boolean> add(@ApiParam("集成测试新增模型") @RequestBody @Valid IntegrationTestAdd record) {
        try {
            return ResultDtoUtil.success(service.addIntegrationTest(record));
        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultDtoUtil.error("新增失败" + e.getMessage());
        }
    }

    /**
     * 修改集成测试
     * @param record
     * @return
     */
    @PutMapping
    @ApiOperation(notes = "修改集成测试", value = "修改集成测试")
    public ResultDto<Boolean> modify(@ApiParam("集成测试修改模型") @RequestBody @Valid IntegrationTestModify record) {
        try {
            return ResultDtoUtil.success(service.modifyIntegrationTest(record));
        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultDtoUtil.error("修改失败" + e.getMessage());
        }
    }


    /**
     * 根据集成测试Id查询集成测试
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    @ApiOperation(notes = "根据集成测试ID查询集成测试(配置详情)", value = "根据集成测试ID查询集成测试(配置详情)")
    public ResultDto<IntegrationTest> getTestConfigDetail(@ApiParam("集成测试ID") @PathVariable String id) {
        return ResultDtoUtil.success(service.selectByPrimaryKey(id));
    }

    int defaultExecuteCount = 1;

    ///**
    // * 根据集成测试Id查询集成测试
    // *
    // * @param id
    // * @return
    // */
    //@PostMapping("{id}/{concurrentCount}")
    //@ApiOperation(notes = "执行集成测试", value = "执行集成测试")
    //public ResultDto<Boolean> execute(@ApiParam(value = "集成测试ID", required = true) @PathVariable String id, @ApiParam(value = "并发数", required = true) @PathVariable int concurrentCount) {
    //    return ResultDtoUtil.success(service.execute(id, defaultExecuteCount, concurrentCount));
    //}

    @PutMapping("execute/{concurrentCount}")
    @ApiOperation(notes = "批量执行集成测试", value = "批量执行集成测试")
    public ResultDto<Boolean> batchExecute(@RequestBody List<String> ids, @ApiParam(value = "并发数", required = true) @PathVariable int concurrentCount) {
        ResultDto<Boolean> result;
        try {
            for (String id : ids) {
                service.execute(id, defaultExecuteCount, concurrentCount);
            }
            result = ResultDtoUtil.success();
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            result = ResultDtoUtil.error(500, "批量删除历史记录错误");
        }
        return result;
    }

    /**
     * 集成测试状态
     *
     * @return
     */
    @GetMapping("record/status")
    @ApiOperation(notes = "获取所有集成测试状态", value = "获取所有集成测试状态")
    public ResultDto<Map<Integer, String>> getStatus() {
        return ResultDtoUtil.success(integrationTestRecordService.getStatus());
    }

    /**
     * 根据集成测试ID查询集成测试(测试记录详情)今日
     *
     * @param params
     * @return
     */
    @GetMapping("record/page/today")
    @ApiOperation(notes = "根据集成测试ID查询集成测试(测试记录详情)今日", value = "根据集成测试ID查询集成测试(测试记录详情)今日")
    public ResultDto<PageInfo<IntegrationTestRecordPage>> getTestRecordDetailToday(@ModelAttribute IntegrationTestRecordPageParams params) {
        ResultDto<PageInfo<IntegrationTestRecordPage>> result;
        try {
            params.setFlag(true);
            PageInfo<IntegrationTestRecordPage> mbrValues = integrationTestRecordService.pageFind(params.getPageNum(), params.getPageSize(), params);
            result = ResultDtoUtil.success(mbrValues);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            result = exceptionHandleIntegrationTestRecordPage.exceptionGet(ex);
        }
        return result;
    }

    /**
     * 根据集成测试ID查询集成测试(测试记录详情)历史
     *
     * @param params
     * @return
     */
    @GetMapping("record/page/history")
    @ApiOperation(notes = "根据集成测试ID查询集成测试(测试记录详情)历史", value = "根据集成测试ID查询集成测试(测试记录详情)历史")
    public ResultDto<PageInfo<IntegrationTestRecordPage>> getTestRecordDetailHistory(@ModelAttribute IntegrationTestRecordPageParams params) {
        ResultDto<PageInfo<IntegrationTestRecordPage>> result;
        try {
            params.setFlag(false);
            PageInfo<IntegrationTestRecordPage> mbrValues = integrationTestRecordService.pageFind(params.getPageNum(), params.getPageSize(), params);
            result = ResultDtoUtil.success(mbrValues);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            result = exceptionHandleIntegrationTestRecordPage.exceptionGet(ex);
        }
        return result;
    }

    /**
     * 根据集成测试ID查询集成测试(测试记录详情)历史
     *
     * @param params
     * @return
     */
    @GetMapping("record/page/all")
    @ApiOperation(notes = "根据集成测试ID查询集成测试(测试记录详情)所有", value = "根据集成测试ID查询集成测试(测试记录详情)所有")
    public ResultDto<PageInfo<IntegrationTestRecordPage>> getTestRecordDetailAll(@ModelAttribute IntegrationTestRecordPageParams params) {
        ResultDto<PageInfo<IntegrationTestRecordPage>> result;
        try {
            params.setFlag(null);
            ConfigManager config = configManagerService.selectConfig();
    		params.setRecordDay(config.getRecordTime());
            PageInfo<IntegrationTestRecordPage> mbrValues = integrationTestRecordService.pageFind(params.getPageNum(), params.getPageSize(), params);
            result = ResultDtoUtil.success(mbrValues);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            result = exceptionHandleIntegrationTestRecordPage.exceptionGet(ex);
        }
        return result;
    }

    /**
     * 根据集成测试接口id获取集成测试用例调用结果集
     *
     * @param asso
     * @return
     */
    @GetMapping("/record")
    @ApiOperation(notes = "获取集成测试用例调用结果集", value = "获取集成测试用例调用结果集")
    public ResultDto<List<InterfaceTestUseCaseTestStatusVO>> getUseCaseExecuteStatusByItirId(@ModelAttribute IntegrationTestInterfaceUseCaseRecordAsso asso) {
        return ResultDtoUtil.success(testUseCaseService.getUseCaseExecuteStatusByItirId(asso));
    }

    /**
     * @param ids 集成测试记录ID
     * @return
     * @Author UaenaSA
     */
    @DeleteMapping("/record")
    @ApiOperation(notes = "批量删除历史记录", value = "批量删除历史记录")
    public ResultDto<Boolean> deleteTask(@RequestBody List<String> ids) {
        ResultDto<Boolean> result;
        try {
            ids.forEach(id -> integrationTestRecordService.deleteByPrimaryKey(id));
            result = ResultDtoUtil.success();
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            result = ResultDtoUtil.error(500, "批量删除历史记录错误");
        }
        return result;
    }

    /**
     * 任务调度批量启用、禁用状态修改
     *
     * @param paramList
     * @return ResultDto<Integer>
     * @author yegui
     * @date 2018年12月17日
     */
    @PostMapping("/batchUpdateStatus")
    @ApiOperation(notes = "集成测试批量启用、禁用状态修改", value = "集成测试批量启用、禁用状态修改")
    public ResultDto<Integer> batchUpdateStatus(@ApiParam @RequestBody @Valid List<IntegrationTestModifyStatus> paramList) {
        ResultDto<Integer> result;
        try {
            service.batchUpdateStatus(paramList);
            result = ResultDtoUtil.success();
        } catch (Exception e) {
            logger.error("批量更新调度状态异常", e);
            result = ResultDtoUtil.error(500, "批量更新调度状态失败");
        }
        return result;
    }
}
